package org.lavemylogic.friendsfinder;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.facebook.AppEventsLogger;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import org.lavemylogic.friendsfinder.controller.CustomRequest;
import org.lavemylogic.friendsfinder.utilities.CustomAlert;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;

public class MainActivity extends Activity {
	
	/*
	 * FB login button.
	 */
    private LoginButton _loginButton;
    
    private Button _showMapButton;
    
    /*
     * FB image widget.
     */
    private ProfilePictureView _profilePictureView;
    
    /*
     * Says hi when logged in, maybe we don`t need it.
     */
    private TextView greeting;
    
    /*
     * FB logged in user.
     */
    private GraphUser _user;
    
    /*
     * https://developers.facebook.com/docs/reference/android/current/UiLifecycleHelper/
     */
    private UiLifecycleHelper _uiHelper;
    
    /*
     * Sets the friends of the logged in user.
     */
    
    public GraphUser getUser() {
    	return _user;
    }
    
    public void setFriends(List<GraphUser> friends) {
    	_user.setProperty("friends", friends);
    }

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.d("HelloFacebook", "Success!");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        _uiHelper = new UiLifecycleHelper(this, callback);
        _uiHelper.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        
        _loginButton = (LoginButton) findViewById(R.id.login_button);
        _showMapButton = (Button) findViewById(R.id.button1);
        
        

        _showMapButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, MapActivity.class);
	            startActivity(intent);
				finish();
			}
		});
        
        _loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
                MainActivity.this._user = user;
                updateUI();
                getFriends();
                
            }
        });

        _profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);
        greeting = (TextView) findViewById(R.id.greeting);
        
        //for(GraphUser friend : (List<GraphUser>) _user.getProperty("friends")) {
        	//GoogleMapController.setMarker(friend.getLocation().getLatitude(), friend.getLocation().getLongitude());
        //}

    }

    @Override
    protected void onResume() {
        super.onResume();
        _uiHelper.onResume();

        // Call the 'activateApp' method to log an app event for use in analytics and advertising reporting.  Do so in
        // the onResume methods of the primary Activities that an app may be launched into.
        AppEventsLogger.activateApp(this);

        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        _uiHelper.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        _uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        _uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        _uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if ((exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
                CustomAlert.showWithButton(MainActivity.this, R.string.cancelled, R.string.permission_not_granted, R.string.ok);
        }
        updateUI();
        
    }

    private void updateUI() {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        if (enableButtons && _user != null) {
            _profilePictureView.setProfileId(_user.getId());
            greeting.setText(getString(R.string.hello_user, _user.getFirstName()));
        } else {
            _profilePictureView.setProfileId(null);
            greeting.setText(null);
        }
    }
    
    private void getFriends() {
    	Session session = Session.getActiveSession();
    	boolean enableButtons = (session != null && session.isOpened());
    	
    	if (enableButtons && _user != null) {
            CustomRequest.getFriends(this);
        }
    	
    }
    
    public void showMapActivity() {
    	Intent intent = new Intent(MainActivity.this, MapActivity.class);
        startActivity(intent);
    	finish();
    }
    
}